/* 
 * Copyright (C) 2003 Heiko Noordhof <heiko.noordhof@xs4all.nl>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * A copy of the GNU General Public License (GPL) is found in the
 * COPYING file that is distributed with this program.
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#include "serctrl.h"


void signalhandler(int sig)
{
     closeserial();
     fprintf(stderr, "Received signal %d. Exit...\n", sig);
     exit(EXIT_FAILURE);
}


void initsignalhandlers(void)
{
     struct sigaction sa;

     memset(&sa, 0, sizeof(sa));
     sa.sa_handler = signalhandler;
     sigaction(SIGHUP, &sa, NULL);
     sigaction(SIGINT, &sa, NULL);
     sigaction(SIGTERM, &sa, NULL);
     sigaction(SIGUSR1, &sa, NULL);
     sigaction(SIGUSR2, &sa, NULL);
     sigaction(SIGPOLL, &sa, NULL);
     sigaction(SIGSYS, &sa, NULL);
}


void switchaction(switx sw)
{
     /* 
      * Do the things here that you want the different
      * switches to do when they are pressed or released.
      * 
      * The struct switx (defined in serctrl.h) has 2 members:
      *  - level: Indicates if the switch was pressed or re-
      *           leased: "on" (non-zero) or "off" (zero).
      *  - nr:    Number of the switch that changed level:
      *             1 = DCD (pin #1)
      *             2 = DSR (pin #6)
      *             3 = CTS (pin #8)
      *             4 = RNG (pin #9)
      *    (pin numbers are for 9-pin (PC) serial port connector)
      */

     /* For demonstration, just print what happened. */
     if (sw.level == on) {
	  printf("Switch #%d PRESSED.\n", sw.nr);
     } else {
	  printf("Switch #%d RELEASED.\n", sw.nr);
     }
}


int main(int argc, char **argv)
{
     char *dev = argc-1?argv[1]:"/dev/ttyUSB0";
     switx sw;
     int level = argc-2?atoi(argv[2]):0;

     if(argc<3)
     {
       printf("\nserswitch v%s.\n", VERSION);
       printf("Usage:  serswitch <serial device> <1/0>\n");
       return 0;
     }
     openserial(dev);
     initsignalhandlers();
     printf("Setting %s RTS level to %d\n", dev, level);
     setRTS(level);
/*     while (1) {
	  sw = waitswitch();
 	  switchaction(sw);
     }
*/
     /* We don't get here.  Anyways: */
     closeserial();

     return 0;
}
